// pages/mine/advice/advice.js
const recorderManager = wx.getRecorderManager();
var app = getApp();
var md5 = require('../../../libs/md5.js');
var myaudio = wx.createInnerAudioContext();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    is_clock: false,
    startPoint: '',
    luyinpop: false,
    startPoint: '',
    yiluyin: false,
    yuyinsrc: [],
    luyintime:[],
    playing:[],
    id:'',
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var id = options.id;
    this.setData({
      id:id
    })
    this.luyin = this.selectComponent("#luyin");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /******语音描述-录音******/
  luyintap: function (e) {
    this.luyin.luyin();
  },

  // 开始录音
  handleRecordStart: function (e) {
    console.log(e)
    this.setData({
      is_clock: true,//长按时应设置为true，为可发送状态
      startPoint: e.detail.e.touches[0],//记录触摸点的坐标信息
      luyinzhong: true,//录音跳动
    })
    //设置录音参数
    const options = {
      duration: 300000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    }
    //开始录音
    recorderManager.start(options);
  },
  // 松开发送
  handleRecordStop: function (e) {
    recorderManager.stop()//结束录音
    //此时先判断是否需要发送录音
    
      var that = this
      //对停止录音进行监控
      recorderManager.onStop((res) => {
        console.log(res)
        if (that.data.is_clock == true) {
            //对录音时长进行判断，少于2s的不进行发送，并做出提示
            if (res.duration < 2000) {
              wx.showToast({
                title: '录音时间太短，请长按录音',
                icon: 'none',
                duration: 1000
              })
            } else {

              var yuyinsrc = res.tempFilePath;
              var luyintime = Math.floor(res.duration / 1000);
              var timestamp = Date.parse(new Date()) / 1000;
              var random = Math.floor(Math.random() * 100);
              var sign = 'GHRDY65' + String(random) + String(timestamp);
              sign = md5.hexMD5(sign);
              wx.showLoading({
                title: '上传中',
              })
              wx.uploadFile({
                url: app.static.url + 'api/common/uploadFile',
                filePath: yuyinsrc,
                name: 'file',
                formData: {
                  timestamp: timestamp,
                  random: random,
                  sign: sign
                },
                success: function (e) {
                  console.log(e);
                  var data = e.data;
                  data = JSON.parse(data);
                  wx.hideLoading()
                  that.setData({
                    yuyinsrc: that.data.yuyinsrc.concat(data.data.url),
                    luyintime: that.data.luyintime.concat(luyintime),
                    playing: that.data.playing.concat(0),
                    yiluyin: true
                  });
                }
              })

            }
        }
        
      })
    
  },
  // 滑动取消发送
  handleTouchMove: function (e) {
    //计算距离，当滑动的垂直距离大于25时，则取消发送语音
    if (Math.abs(e.detail.touches[0].clientY - this.data.startPoint.clientY) > 30) {
      this.setData({
        is_clock: false,//设置为不发送语音
        luyinpop: false,
        luyinzhong: false
      })
    }
  },
  
  // 播放录音
  playluyin: function (e) {
    console.log(e)
    var datasrc = e.currentTarget.dataset.src;
    var index = e.currentTarget.dataset.index;
    var that = this;
    var playing = that.data.playing;
    for (var i = 0; i < playing.length; i++) {
      playing[i] = 0;
    }
    myaudio.pause();
    myaudio.src = datasrc;

    if (playing[index] == 0) {
      myaudio.play();
      playing[index] = 1;
      that.setData({
        playing: playing
      })
      myaudio.onEnded(function () {
        console.log(1)
        playing[index] = 0;
        that.setData({
          playing: playing
        })
      })
    } else {
      myaudio.pause();
      playing[index] = 0;
      that.setData({
        playing: playing
      })
    }

  },

  delluyin: function (e) {
    var that = this;
    var yuyin = that.data.yuyinsrc;
    var luyintime = that.data.luyintime;
    var index = e.currentTarget.dataset.index; //获取当前按图片下标
    wx.showModal({
      title: '提醒',
      content: '确定要删除此录音吗？',
      success: function (res) {
        if (res.confirm) {
          yuyin.splice(index, 1);
          luyintime.splice(index, 1);
        } else if (res.cancel) {
          return false;
        }
        that.setData({
          yuyinsrc: yuyin,
          luyintime: luyintime
        });
      }
    })
  },


  tijiao: function (e) {
    console.log(e)
    var price = e.detail.value.price;
    price = Math.floor(price * 100) / 100;  
    var content = e.detail.value.content;
    var userid = wx.getStorageSync("userId");
    if (price == '' || content == '') {
      wx.showToast({
        title: '请将数据补充完整',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    var voice_len = this.data.luyintime;
    voice_len = voice_len.join(',');
    var yuyinsrc = this.data.yuyinsrc;
    yuyinsrc = yuyinsrc.join(',');
    var jianyi = {
      price: price,
      answer: content,
      user_id: userid,
      voice_len:voice_len,
      voice:yuyinsrc,
      grab_orders_id:this.data.id
    }
    // wx.showLoading({
    //   title: '提交中，请耐心等待。。。'
    // })

    if (wx.showLoading) {
      wx.showToast({
        icon: 'loading',
        title: '提交中，请耐心等待。。。',
        mask: true
      })
    };
  
      var jypost = {
        url: "api/shop/baojia",
        data: jianyi,
        success: function (e) {
          wx.hideLoading()
          wx.showToast({
            title: e.data.msg,
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            if (e.data.code == 1) {
              wx.redirectTo({
                url: '/pages/shangjia/shangjia/shangjia',
              })
            }
          }, 1000)
        },
        error: function (e) {
          wx.hideLoading()
          wx.showToast({
            title: e.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      };
      app.post(jypost);
   

  },
  goback:function(){
    var pages = getCurrentPages();
    var beforePage = pages[pages.length - 2];
    beforePage.getorder(this.data.id);
    wx.navigateBack({
      delta:1
    })
  }

})